package com.pet.admin.controller;


import com.pet.admin.mapper.BannerMapper;
import com.pet.admin.model.Banner;
import com.pet.admin.model.BannerExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;



@RestController
public class FileController {
    @Autowired
    private BannerMapper bannerMapper;

    @RequestMapping(value="/banner/upload",method = RequestMethod.POST)
   public String uploadBanner(HttpServletRequest request) {
      List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("banner[]");
      MultipartFile file = null;
      BufferedOutputStream stream = null;
      bannerMapper.deleteByExample(new BannerExample());
      for (int i = 0; i < files.size(); ++i) {
          file = files.get(i);
          if (!file.isEmpty()) {
              try {
                  byte[] bytes = file.getBytes();
                  String name = file.getOriginalFilename();
                  stream = new BufferedOutputStream(new FileOutputStream(
                          new File("D:/"+name)));

                  stream.write(bytes);
                  stream.close();
                  Banner banner = new Banner();
                  banner.setName(name);
                  bannerMapper.insertSelective(banner);
              } catch (Exception e) {
                  stream = null;
                  return "You failed to upload " + i + " => "
                          + e.getMessage();

              }
          } else {
              return "You failed to upload " + i
                      + " because the file was empty.";
          }

      }
      return "{}";
  }

}